from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import json
from selenium.webdriver.common.by import By
import time
import topic_handling as ht
import connection_Kimi as km


# 加载cookie文件信息
def load_cookies(driver, path):
    with open(path, 'r') as cookiesfile:
        cookies = json.load(cookiesfile)
    for cookie in cookies:
        driver.add_cookie(cookie)


def go_homework():
    # 初始化URL 浏览器界面
    driver = webdriver.Chrome()
    driver.get("https://www.eduplus.net/course/course/ac583695451c43779c1bdb042ebc465b/HomeworkPage?userRole=")
    load_cookies(driver, "cookies.json")  # 加载登陆文件
    driver.refresh()  # 刷新页面使Cookie生效
    # 点击去做作业界面
    wait = WebDriverWait(driver, 10)
    father_element = wait.until(
        EC.element_to_be_clickable(
            (By.XPATH, '/html/body/div[1]/div[1]/div[1]/div[2]/div[2]/div/div/div/div'))
    )
    original_window = driver.current_window_handle
    son_elements = father_element.find_elements(By.CSS_SELECTOR, ".list-container")
    for element in son_elements:
        try:
            # 查找并点击"去做作业"按钮
            go_work = element.find_element(By.CSS_SELECTOR, ".do-homwork")
            # 使用JavaScript点击，避免元素被遮挡的问题
            driver.execute_script("arguments[0].click();", go_work)
            # 等待新窗口出现
            new_window = wait.until(
                lambda d: len(d.window_handles) > 1,
                message="超时未检测到新窗口打开"
            )
            # 切换到新窗口
            new_window_handle = [w for w in driver.window_handles if w != original_window][0]
            driver.switch_to.window(new_window_handle)
            # 等待页面加载完成
            wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
            # 在这里执行新窗口中的操作
            go_topic(driver)
            time.sleep(3)
            # 操作完成后关闭新窗口
            driver.close()
            # 切换回原始窗口
            driver.switch_to.window(original_window)
        except Exception as e:
            # 确保当前窗口是原始窗口
            try:
                driver.switch_to.window(original_window)
            except:
                # 如果原始窗口句柄无效，重新获取
                original_window = driver.window_handles[0]
                driver.switch_to.window(original_window)
            continue


def go_topic(driver):
    # 获取可用的值
    parent_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[1]/div[1]/div[2]/div[1]/div[2]/div[1]/div"))
    )
    time.sleep(1)
    child_elements = parent_element.find_elements(By.CSS_SELECTOR, "div[data-v-1ad0c15a].flex.flex-col.w-full")

    child_elements = child_elements[1:]
    for item in child_elements:
        try:
            item.click()
            time.sleep(0.5)  # 停止等待页面加载完成 根据网络速度或者浏览器响应速度来决定等待时间
            topic_type = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (
                        By.XPATH,
                        '//*[@id="exercise_content_area"]/div[1]/div[1]/div/div/div/div[1]/div[1]/div[1]/div[2]'))
            )
            topic = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH,
                                                "/html/body/div[1]/div[1]/div[1]/div[2]/div[2]/div/div/div[1]/div[1]/div/div/div/div[1]/div[2]/p"))
            )
            topic_data = {}
            if topic_type.text == "单选题" or topic_type.text == "多选题":
                topic_data = ht.driver_func(topic, topic_type, driver)
                ans = km.kimi(topic_data)
                # 判断选项是否包含 有就选择这个选项
                ht.select_options(driver, ans)

            elif topic_type.text == "判断题":
                topic_data = ht.driver_func(topic, topic_type, driver)
                ans = km.kimi(topic_data)
                ht.select_options(driver, ans)

            elif topic_type.text == '填空题':
                topic_data = ht.driver_func(topic, topic_type, driver)
                ans = km.kimi(topic_data)
                print(ans)
                ht.tian_kong(driver, ans)
        except Exception as e:
            print(e)
if __name__ == "__main__":
    go_homework()
